<template>
  <div class="desktop" ref="desktopRef">
    <div class="top">
      <el-dropdown trigger="click">
        <div class="logo">
          <i class="iconfont icon-apple1"></i>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="openAppByKeyHandle('system_about')">
              <div>关于本站</div>
            </el-dropdown-item>
            <el-dropdown-item class="line"></el-dropdown-item>
            <el-dropdown-item @click="openAppByKeyHandle('system_setting')">
              <div>系统偏好设置</div>
            </el-dropdown-item>
            <el-dropdown-item @click="openAppByKeyHandle('system_store')">
              <div>应用商店</div>
            </el-dropdown-item>
            <el-dropdown-item class="line"></el-dropdown-item>
            <el-dropdown-item @click="openAppByKeyHandle('system_task')">
              <div>强制退出...</div>
            </el-dropdown-item>
            <el-dropdown-item class="line"></el-dropdown-item>
            <el-dropdown-item @click="shutdown">
              <div>关机...</div>
            </el-dropdown-item>
            <el-dropdown-item class="line"></el-dropdown-item>
            <el-dropdown-item @click="lockScreen">
              <div>锁定屏幕</div>
            </el-dropdown-item>
            <el-dropdown-item @click="logout">
              <div>退出登录 {{ loginInfo?.name }}</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="menu" v-for="item in menu" :key="item.value">
        <el-dropdown trigger="click" placement="bottom-start">
          <div class="item">{{ item.title }}</div>
          <template #dropdown>
            <el-dropdown-menu>
              <template v-for="subItem in item.sub" :key="subItem.value">
                <el-dropdown-item class="line" v-if="subItem.isLine"></el-dropdown-item>
                <el-dropdown-item v-else @click="onClickMenu(subItem.key)">
                  <div>{{ subItem.title }}</div>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="space"></div>
      <div class="status">
        <!-- <div class="audio">
          <i
            class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-39"
            @click="showOrHideVolumn"
          ></i>

          <transition name="fade">
            <el-slider
              v-show="isVolumnShow"
              v-model="volumn"
              :show-tooltip="false"
              vertical
            ></el-slider>
          </transition>
        </div> -->
        <div class="datetime" @click.self="showOrHideCalendar">
          {{ timeString }}
          <transition name="fade">
            <el-calendar v-model="nowDate" v-if="isCalendarShow"></el-calendar>
          </transition>
        </div>
        <div class="notification">
          <i
            class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-25"
            @click="showOrHideWidget"
          ></i>
        </div>
      </div>
    </div>
    <div
      class="body"
      @contextmenu.prevent.self="
        hideAllController();
        openMenuHandle($event);
      "
      @click.stop="hideAllController()"
    >
      <div class="desktop-app">
        <template v-for="item in deskTopAppList" :key="item.key">
          <div
            class="app-item"
            v-on:dblclick="openApp(item)"
            v-if="
              !item.hideInDesktop &&
              (!item.mustAdmin || (item.mustAdmin && loginInfo.userType == '超级管理员'))
            "
          >
            <div class="icon">
              <i
                :style="{
                  backgroundColor: item.iconBgColor,
                  color: item.iconColor,
                }"
                class="iconfont"
                :class="item.icon"
              ></i>
            </div>
            <div class="title">{{ item.title }}</div>
          </div>
        </template>
      </div>
      <transition-group name="fade-window">
        <template v-for="item in openAppList" :key="item.pid">
          <App v-if="!item.outLink" v-show="!item.hide" :app="item" :key="item.pid"></App>
        </template>
      </transition-group>
      <transition name="fade-menu">
        <div
          v-show="rightMenuVisible"
          :style="{ left: rightMenuLeft + 'px', top: rightMenuTop + 'px' }"
          class="contextmenu"
        >
          <div @click="lockScreen">锁定屏幕...</div>
          <hr />
          <div @click="openAppByKeyHandle('system_setting')">系统偏好设置...</div>
          <div @click="openAppByKeyHandle('system_task')">强制退出...</div>
          <hr />
          <!-- <div @click="$message.warning('即将上线，敬请期待')">设置壁纸...</div> -->
          <div @click="openAppByKeyHandle('system_about')">关于我们</div>
        </div>
      </transition>
      <transition-group name="fade-widget">
        <div v-show="isWidgetShow">
          <template v-for="item in openWidgetList" :key="item.pid">
            <Widget
              v-if="!item.outLink"
              v-show="!item.hide"
              :app="item"
              :key="item.pid"
            ></Widget>
          </template>
        </div>
      </transition-group>
    </div>
    <Dock></Dock>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, defineEmits } from "vue";
import { useAppStore } from "@/store/modules/app";
import { storeToRefs } from "pinia";
import { useCommonStore } from "@/store/modules/common";
import * as SignalR from "@microsoft/signalr";
import config from "@/config/config";
import storage from "@/utils/storage";
import bus from "vue3-eventbus";
import eventKey from "@/const/busEventConstKey";
import { ElNotification } from "element-plus";

import App from "@/components/App.vue";
import Dock from "@/components/Dock.vue";
import Widget from "@/components/Widget.vue";
import tool from "@/helper/tool";

const isCalendarShow = ref(false);
const nowDate = ref(new Date());
// const volumnDelayTimer = ref(false);
const volumn = ref(80);
const isVolumnShow = ref(false);
const rightMenuVisible = ref(false);
const rightMenuLeft = ref(0);
const rightMenuTop = ref(0);
const userName = ref("");
const menu = ref<any[]>([]);
const timeString = ref("");
const deskTopAppList = ref<any[]>([]);
const deskTopMenu = ref([]);
const isWidgetShow = ref(false);
const desktopRef = ref<any>(null);

const appStore = useAppStore();
const { openWidgetList, openAppList, nowApp, launchpad } = storeToRefs(appStore);
const { openApp, openMenu, openAppByKey, getDockAppList, launchpadToggle } = appStore;

const commonStore = useCommonStore();
const { loginInfo } = storeToRefs(commonStore);
const { loadAllSetting, getLoginInfo } = commonStore;
console.log(loginInfo);

const emits = defineEmits(["lockScreen", "shutdown", "logout"]);
watch(
  () => volumn,
  () => {
    // this.$store.commit("setVolumn", this.volumn);
    // clearTimeout(this.volumnDelayTimer);
    // this.volumnDelayTimer = setTimeout(() => {
    //   this.isVolumnShow = false;
    // }, 3000);
  }
);

watch(
  () => nowApp.value,
  () => {
    menu.value = nowApp.value.menu;
  }
);
watch(
  () => launchpad.value,
  () => {
    launchpadToggle();
  }
);

menu.value = deskTopMenu.value;
userName.value = "123";
deskTopAppList.value = tool.getDeskTopApp();
startTimer();
getDockAppList();

/**
 * @description: 显示或隐藏日历
 */
function showOrHideCalendar() {
  isCalendarShow.value = !isCalendarShow.value;
}

// /**
//  * @description: 显示或隐藏音量操作
//  */
// function showOrHideVolumn() {
//   isVolumnShow.value = !isVolumnShow.value;
//   if (isVolumnShow.value) {
//     clearTimeout(volumnDelayTimer.value);
//     volumnDelayTimer.value = setTimeout(() => {
//       isVolumnShow.value = false;
//     }, 3000);
//   }
// }

/**
 * @description: 隐藏所有弹出的控制器
 */
function hideAllController() {
  isVolumnShow.value = false;
  rightMenuVisible.value = false;
  isCalendarShow.value = false;
}

/**
 * 点击顶部菜单
 * @param key
 */
function onClickMenu(key) {
  openMenu(key);
}

/**
 * @description: 打开右键菜单
 */
function openMenuHandle(e) {
  const menuMinWidth = 105;
  const offsetLeft = desktopRef.value.getBoundingClientRect().left; // container margin left
  const offsetWidth = desktopRef.value.offsetWidth; // container width
  const maxLeft = offsetWidth - menuMinWidth; // left boundary
  const left = e.clientX - offsetLeft; // margin right

  if (left > maxLeft) {
    rightMenuLeft.value = maxLeft;
  } else {
    rightMenuLeft.value = left;
  }

  rightMenuTop.value = e.clientY - 30;
  rightMenuVisible.value = true;
}

/**
 * @description: 打开时间计时器
 */
function startTimer() {
  setInterval(() => {
    timeString.value = tool.formatTime(new Date(), "MM-dd HH:mm:ss");
  }, 1000);
}

/**
 * @description: 打开指定key的应用
 */
function openAppByKeyHandle(key) {
  openAppByKey(key);
}
/**
 * @description: 锁定屏幕
 */
function lockScreen() {
  emits("lockScreen");
}
/**
 * @description: 关机
 */
function shutdown() {
  emits("shutdown");
}
/**
 * @description: 注销登录
 */
function logout() {
  emits("logout");
}
function showOrHideWidget() {
  isWidgetShow.value = !isWidgetShow.value;
}

async function initDesktop() {
  await loadAllSetting();
  await getLoginInfo();

  const accessTokenKey = "access-token";
  //初始化signalr HubConnection对象
  const connection = new SignalR.HubConnectionBuilder()
    .configureLogging(SignalR.LogLevel.Information)
    .withUrl(
      `${config.apiBaseUrl}/hubs/logHub?access_token=${storage.getItem(accessTokenKey)}`
    )
    .withAutomaticReconnect({
      nextRetryDelayInMilliseconds: () => {
        //每5秒重连一次
        return 5000;
      },
    })
    .build();
  connection.keepAliveIntervalInMilliseconds = 15000; //定时PING服务器，避免掉线
  connection.on("ReceiveMessage", (data: any) => {
    console.log(data);
    if (data.messageType == 2) {
      ElNotification({
        title: data.title,
        message: data.message,
        type: "success",
      });
    } else {
      bus.emit(eventKey.receiveMessage, data);
    }
  });
  connection.onclose(() => {
    //连接断开
    console.log("连接断开");
  });
  connection.onreconnecting(() => {
    //掉线重连中
    console.log("掉线重连中");
  });
  connection.onreconnected(() => {
    //重新连接成功
    console.log("重新连接成功1");
  });
  connection.start().then(() => {
    //第一次连接成功
  });
}
initDesktop();
</script>
<style>
.top .el-dropdown {
  color: white !important;
  height: 100% !important;
}
.top .el-calendar-day {
  height: 30px !important;
}
.top .is-today {
  background: #4b9efb !important;
  color: white !important;
}
</style>
<style scoped lang="scss">
.desktop {
  display: flex;
  flex-direction: column;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: white;
  overflow: hidden;
  text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
  .top {
    height: 28px;
    background-color: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(20px);
    display: flex;
    flex-direction: row;
    font-size: 14px;
    align-items: center;
    justify-content: center;
    padding: 0px 5px;
    z-index: 100;
    .logo {
      height: 100%;
      align-items: center;
      justify-content: center;
      padding: 0px 15px;
      cursor: pointer;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      .iconfont {
        font-size: 16px;
        margin-top: -3px;
      }
      .el-select {
        position: absolute;
        opacity: 0;
      }
    }

    .logo:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }
    .space {
      flex-grow: 1;
    }
    .menu {
      display: flex;
      flex-direction: row;
      font-size: 13px;
      height: 100%;
      font-weight: 500;
      .item {
        font-size: 13px;
        padding: 0px 15px;
        display: inline-block;
        flex-grow: 1;
        cursor: pointer;
        display: flex;
        height: 100%;
        align-items: center;
        justify-content: center;
      }
      .item:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }
    }

    .status {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      height: 100%;

      .audio {
        cursor: pointer;
        padding: 0px 10px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        position: relative;
        .iconfont {
          font-size: 20px;
        }
        .el-slider {
          position: absolute;
          top: 40px;
          height: 80px;
        }
      }
      .audio:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }
      .datetime {
        cursor: pointer;
        padding: 0px 10px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        position: relative;
        .el-calendar {
          color: #333;
          background: rgba(255, 255, 255, 0.98);
          position: fixed;
          top: 40px;
          right: 20px;
          width: 500px;
          border-radius: 10px;
        }
      }
      .datetime:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }
      .notification {
        cursor: pointer;
        padding: 0px 10px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        .iconfont {
          font-size: 20px;
        }
        .notification:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
    }
  }

  .body {
    flex-grow: 1;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: relative;
    .desktop-app {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-end;
      padding: 20px;
      flex-wrap: wrap-reverse;
      .app-item {
        padding: 10px 0px;
        flex-direction: column;
        text-align: center;
        text-shadow: 0px 0px 2px rgb(0 0 0 / 50%);
        cursor: pointer;
        border-radius: 10px;
        border: 2px solid transparent;
        justify-content: center;
        align-items: center;
        width: 80px;
        .icon {
          border-radius: 10px;
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;
        }
        .iconfont {
          font-size: 28px;
          border-radius: 10px;
          padding: 8px;
        }
        .title {
          font-size: 12px;
          margin-top: 5px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
      .app-item:hover {
        border: 2px solid rgba(255, 255, 255, 0.5);
      }
    }

    .contextmenu {
      position: absolute;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 5px;
      box-shadow: 0px 0px 10px rgb(0 0 0 / 30%);
      color: #333;
      font-size: 14px;
      text-align: left;
      width: 200px;
      overflow: hidden;
      padding: 2px 0px;
      text-shadow: none;
      z-index: 100;
      hr {
        border: none;
        border-top: 1px solid #ddd;
      }
      div {
        cursor: pointer;
        font-size: 13px !important;
        color: #333;
        border-radius: 5px;
        line-height: 2;
        padding: 0px 12px;
        display: flex;
        align-items: center;
        margin: 3px 5px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      div:hover {
        background: #4b9efb;
        color: white;
        border-radius: 5px;
      }
    }
  }
  .footer {
    display: flex;
    z-index: 100;
  }
}
</style>
